/*
 * TUIOGUIEventHandler.cpp
 *
 *  Created on: Aug 22, 2010
 *      Author: Ry
 */

#include "TUIOGUIEventHandler.h"

using namespace std;

TUIOGUIEventHandler::TUIOGUIEventHandler(GUI *gui, GameWindow *window, vector<Cursor*> *cursors) {
	this->gui = gui;
	this->window = window;
	this->cursors = cursors;
}

void TUIOGUIEventHandler::search(vector<Component*> (*insideCallback)(Component*), vector<Component*> (*outsideCallback)(Component*) = NULL) {
	WindowResolution res = window->getCurrentResolution();
	int x = (int)(res.width * event.x);
	int y = (int)(res.height * (1 - event.y));

	vector<Component*> search = gui->getComponents();
	vector<Component*> nextSearch;

	while (search.size() > 0){
		for (unsigned int i = 0; i < search.size(); i++) {
			Component *component = search[i];
			Cursor *cursor = dynamic_cast<Cursor*>(component);

			if (cursor == NULL) {
				if (component->getRect().inside(x, y)) {
					nextSearch = insideCallback(component);
				} else {
					if (outsideCallback != NULL) {
						nextSearch = outsideCallback(component);
					}
				}
			}
		}
		search = nextSearch;
		nextSearch.clear();
	}
}

vector<Component*> mouseOver(Component *component) {
	vector<Component*> nextSearch;
	vector<Component*> children = component->getChildren();
	if (!component->getHover()) {
		GUIEvent guiEvent;
		guiEvent.type = GUIEvent::MOUSEENTER;
		component->setHover(true);
		component->handleEvent(&guiEvent);
	}
	nextSearch.insert(nextSearch.end(), children.begin(), children.end());
	return nextSearch;
}

vector<Component*> mouseOut(Component *component) {
	vector<Component*> nextSearch;
	vector<Component*> children = component->getChildren();
	if (component->getHover()) {
		GUIEvent guiEvent;
		guiEvent.type = GUIEvent::MOUSEEXIT;
		component->setHover(false);
		component->handleEvent(&guiEvent);
		nextSearch.insert(nextSearch.end(), children.begin(), children.end());
	}
	return nextSearch;
}

void TUIOGUIEventHandler::handleEvent(float dts) {
	if (event.type == TUIOEvent::TUIO_UPDATE_CURSOR) {
		search(mouseOver, mouseOut);
	}
	else if (event.type == TUIOEvent::TUIO_REMOVE_CURSOR) {
		search(mouseOut);
	}
}

TUIOGUIEventHandler::~TUIOGUIEventHandler() {
}
